package com.prp.gwt.client.widgets.user.home;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.prp.gwt.client.user.php.PHPHistoryHandler;
import com.prp.gwt.client.vo.User;
import com.prp.gwt.client.vo.UserList;

public class UserRecommendPanel extends DecoratorPanel {

	private static UserRecommendPanel instance;
	private VerticalPanel innerPanel = new VerticalPanel();
	private Grid table = new Grid(3, 3);
	private Image loadImage = new Image(GWT.getModuleBaseURL() + "loading.gif");

	public static UserRecommendPanel getInstance() {
		return instance;
	}

	public UserRecommendPanel() {
		instance = this;
		addStyleName("userRecommend");
		HTML title = new HTML("他们与你兴趣相近...");
		title.addStyleName("userRecommend-title");
		innerPanel.add(title);
		innerPanel.add(loadImage);
		innerPanel.add(table);
		add(innerPanel);
	}

	public void load(UserList list) {
		loadImage.setVisible(false);
		for (int i = 0; i < list.size() && i < 9; i++) {
			VerticalPanel panel = new VerticalPanel();
			Image image = new Image(list.get(i).getPortrait());
			image.addStyleName("userRecommend-image");
			panel.add(image);
			final User user= list.get(i);
			HTML name = new HTML("<a>" + user.getUsername() + "</a>");
			name.addClickHandler(new ClickHandler(){
				@Override
				public void onClick(ClickEvent event) {
					History.newItem(PHPHistoryHandler.PREFIX_USERHOME+user.getId());
				}
			});
			name.addStyleName("userRecommend-name");
			panel.add(name);
			panel.setCellHorizontalAlignment(name,
					HasHorizontalAlignment.ALIGN_CENTER);
			table.setWidget(i / 3, i % 3, panel);
			if (i / 3 != 2)
				table.getCellFormatter().addStyleName(i / 3, i % 3,
						"userRecommend-item-top");
			if (i % 3 != 2)
				table.getCellFormatter().addStyleName(i / 3, i % 3,
						"userRecommend-item-left");
		}
	}
}
